/**
 * Created by hdt3213 on 16-8-23.
 */

// init

var boardElement;

var indexData = {
    title: '导航',
    text: '',
    buttons: [
        {
            text: '双人', onClick: function () {
            model.startGame();
            status = 1;
        }
        },
        {
            text: '人机', onClick: function () {
            $.modal(autoGameData);
        }
        },
        {
            text: '在线游戏', onClick: function () {
            $.modal(onlineData);
        }
        }
    ]
};

var autoGameData = {
    title: '人机游戏',
    text: '选择先后手',
    buttons: [
        {
            text: '玩家先行', onClick: function () {
            model.startGame();
            autoplayer.role = WHITE;
            status = 2;
        }
        },
        {
            text: '电脑先行', onClick: function () {
            model.startGame();
            autoplayer.role = BLACK;
            status = 2;
            model.newStep(7, 7);
            drawPiece(7, 7, BLACK);
        }
        }
    ]
};

var loginData = {
    title: '登录',
    text: '',
    onOK: function (username, password) {
        login(username, password);
        $.closeModal()
    },
    onCancel: function () {
        $.modal(indexData);
    }
};

var onlineData = {
    title: '导航',
    text: '',
    buttons: [
        {
            text: '登录', onClick: function () {
            $.login(loginData);
        }
        },
        {
            text: '注册', onClick: function () {
            window.open('/static/register.html')
        }
        },
        {
            text: '重设密码', onClick: function () {
            window.open('/static/reset.html')
        }
        }
    ]
};

function initBoard() {
    var step = 35, leftBorder = 3, topBorder = 3;
    var left, top, style;
    for (var i = 0; i < LEN; i++) {
        for (var j = 0; j < LEN; j++) {
            var block = $('<button class="board_block"></button>').text("");
            block.attr("id", "block_" + String(i) + "_" + String(j));
            block.attr('x', j);
            block.attr('y', i);
            top = step * i + topBorder;
            left = step * j + leftBorder;
            style = "left:" + left + "px;top:" + top + "px;";
            block.attr("style", style);
            boardElement.append(block);
        }
    }
}

// update view

function showPartner() {
    $('#board').hide();
    $('#partner').show();
}

function showBoard() {
    $('#partner').hide();
    $('#board').show();
    $('#local_buttons').hide();
    $('#online_buttons').show();
}

function updatePartnerView() {
    var user_info = user.username + ' score: ' + user.score + '\n success: ' + user.success + ' failure: ' + user.failure;
    var partner_info = partner.name + ' score: ' + partner.score + '\n success: ' + partner.success + ' failure: ' + partner.failure;
    $('#partner_info').text(partner_info);
    $('#user_info').text(user_info);
}

function setReadyView(role, ready) {
    if (role == 'partner') {
        if (ready == 1) {
            $('#partner_ready').attr('class', 'weui_icon_msg weui_icon_success');
        }
        else {
            $('#partner_ready').attr('class', 'weui_icon_msg weui_icon_waiting');
        }
    }
    else if (role == 'user') {
        if (ready == 1) {
            $('#user_ready').attr('class', 'weui_icon_msg weui_icon_success');
        }
        else {
            $('#user_ready').attr('class', 'weui_icon_msg weui_icon_waiting');
        }
    }
}

function drawPiece(x, y, role) {
    var block_id = "#block_" + String(y) + "_" + String(x);
    var blockClass = "board_block active black";
    if (role == WHITE) {
        blockClass = "board_block active white"
    }
    $(block_id).attr("class", blockClass);
}

function erasePiece(x, y) {
    var block_id = "#block_" + String(y) + "_" + String(x);
    $(block_id).attr("class", 'board_block');
}

function clearBoard() {
    for (var i = 0; i < LEN; i++) {
        for (var j = 0; j < LEN; j++) {
            var block_id = "#block_" + String(j) + "_" + String(i);
            $(block_id).attr("class", 'board_block');
        }
    }
}

// event

function boardClicked() {
    // update view and model
    var x = $(this).attr("x"), y = $(this).attr("y");
    var role = model.getRole(), result, winner = VACANT;
    // game started validate
    if (!model.gameStarted) {
        return;
    }
    // role validate
    if (status == 2) { // auto
        if (role == autoplayer.role) {
            return null;
        }
    }
    else if (status == 3) {  // online
        if (role != user.role) {
            return null;
        }
    }
    if (model.getPos(x, y) != VACANT) {
        return null;
    }
    model.newStep(x, y);
    drawPiece(x, y, role);
    var step = model.getLastStep();
    // send msg
    if (status == 2) { // send to auto player
        callAutoPlayer();
    }
    else if (status == 3) { // send to partner
        sendNewStep(step);
    }
    // judge winner
    winner = judge(model.getLastStep());
    if (winner == BLACK || winner == WHITE) {
        gameOver(winner);
        return null;
    }
}

function callAutoPlayer() {
    var step = {}, winner = {};
    winner = judge(model.getLastStep());
    if (winner == BLACK || winner == WHITE) {
        gameOver(winner);
        return Null;
    }
    //step = randomReact();
    step = react();
    model.newStep(step.x, step.y);
    drawPiece(step.x, step.y, step.role);
}

function gameOver(winner) {
    if (status == 1) {  // local
        if (winner == BLACK) {
            $.alert('黑方胜')
        }
        else {
            $.alert('白方胜')
        }
        model.gameStarted = 0;
    }
    else if (status == 2) { // auto player
        if (winner == autoplayer.role) {
            $.alert('电脑胜利了')
        }
        else {
            $.alert('您胜利了')
        }
        model.gameStarted = 0;
    }
    else if (status == 3) { // online
        if (winner == user.role) {
            $.alert('您胜利了');
        }
        else {
            $.alert('对方胜利了');
        }
        // clear game
        model.clear();
        clearBoard();
        // setup partner view
        showPartner();
        partner.ready = 0;
        user.ready = 0;
        setReadyView('partner', 0);
        setReadyView('user', 0);
    }
}

function localRetractClicked() {
    if (status == 1) {
        var step = model.retract();
        erasePiece(step[0], step[1]);
    }
    else if (status == 2) {
        if (model.getRole() == autoplayer.role) {
            // cannot retract when autoplayer thinking
            return null;
        }
        else if (model.history.length < 1) {
            return null;
        }
        if (autoplayer.role == BLACK) {
            if (model.history.length == 1) {
                // the first piece of autoplayer cannot be retracted
                return null;
            }
            else if (model.history.length == 2) {
                // the first piece of autoplayer cannot be retracted
                // retract the second piece of human player
                step = model.retract();
                erasePiece(step[0], step[1]);
                return null;
            }
        }
        // retract piece of human player
        step = model.retract();
        erasePiece(step[0], step[1]);
        // retract piece of auto player
        step = model.retract();
        erasePiece(step[0], step[1]);
    }
}

function localRestartClicked() {
    model.startGame();
    clearBoard();
    if (status == 2) {
        if (autoplayer.role == BLACK) {
            model.newStep(7, 7);
            drawPiece(7, 7, BLACK);
        }
    }
}

function readyClicked() {
    if (user.ready == 0) {
        sendReady(1);
        setReadyView('user', 1);
    }
    else {
        sendReady(0);
        setReadyView('user', 0);
    }
}


function retractClicked() {
    $.confirm('确定要悔棋吗?', '提示', function () {
        sendRetractAsk();
    });
}


function resignClicked() {
    $.confirm('确定要认输吗?', '提示', function () {
        sendResign();
    });
}

function signOutClicked() {
    $.confirm('确定要退出吗?', '提示', function () {
        signOut();
    });
}


function partnerRetractAsk() {
    $.confirm('对方请求悔棋',
        function () {
            sendRetractAnswer(1);
            var step = model.retract();
            erasePiece(step[0], step[1]);
        },
        function () {
            sendRetractAnswer(0);
        }
    );
}

// start

$(document).ready(function () {

    $.modal(indexData);

    boardElement = $("#board");

    initBoard();

    $("#online_buttons").hide();

    $("#partner").hide();

    $(".board_block").click(boardClicked);

    $('#local_retract_btn').click(localRetractClicked);

    $('#local_restart_btn').click(localRestartClicked);

    $("#ready_btn").click(readyClicked);

    $("#resign_btn").click(resignClicked);

    $('#retract_btn').click(retractClicked);

    $('#sign_out_btn').click(signOutClicked);


});



